// 路由访问权限
import router from './router'

// 在访问页面之前做些什么
router.beforeEach((to, from, next) => {
  document.title = to.meta.title

  let userInfoStoreage = sessionStorage.getItem('userInfo')
  let userInfo = null
  if (userInfoStoreage) {
    userInfo = JSON.parse(userInfoStoreage)
  }
  
  // 页面需要授权
  if (!to.meta.noAuth) {
    // 没有登录信息
    if (userInfo === null) {
      next('/login')
    } else {
      // 还要判断是否有访问该页面的权限
      let viewPermissions = to.meta.permissions
      // 当前访问的页面是否需要权限
      let needPermission = false

      if (viewPermissions === undefined || !viewPermissions.length) {
        needPermission = false
      } else {
        needPermission = true
      }

      if (needPermission) {
        for (let permission of viewPermissions) {
          // 是否拥有页面的访问权限
          let hasPermission = userInfo.permissions.some(item => item == permission)
          if (hasPermission) next()
          else next('/403')
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
})